//
//  NODataView.m
//  test
//
//  Created by 本来 on 2017/11/13.
//  Copyright © 2017年 本来ss. All rights reserved.
//

#import "JCNODataView.h"

#define JCNoDataLeftMargin (20)
#define JCNoDataViewWidth ([[UIScreen mainScreen] bounds].size.width)
#define JCNoDataViewHeight ([[UIScreen mainScreen] bounds].size.height)

@implementation JCNODataView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addObserver:self forKeyPath:@"isNoData" options:NSKeyValueObservingOptionOld context:nil];
        [self addIconView];
        [self addGesture];
    }
    
    return self;
}

- (instancetype)init {    
    if (self = [super init]) {
        [self addObserver:self forKeyPath:@"isNoData" options:NSKeyValueObservingOptionOld context:nil];
        [self addIconView];
        [self addGesture];
    }
    
    return self;
}

- (void)addIconView {
    UILabel *label = [[UILabel alloc] init];
    [self addSubview:label];
    
    [label setText:@"暂无数据"];
    [label setTextColor:[UIColor blackColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setFrame:CGRectMake(JCNoDataLeftMargin, (JCNoDataViewHeight - 40) / 2.0f, JCNoDataViewWidth - 40, 40)];
}

- (void)addGesture {
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
    [self addGestureRecognizer:recognizer];
}

- (void)handleGesture:(UIPanGestureRecognizer *)recognizer {
    if (self.handleEvent) {
        self.handleEvent(recognizer);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (_isNoData) {
        [self showNoDataView];
    } else {
        [self hiddenNoDataView];
    }
}

- (void)showNoDataView {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        if (weakSelf.selfSuperView) {
            [weakSelf.selfSuperView addSubview:weakSelf];
        }
        
        [self setHidden:NO];
    }];
}

- (void)hiddenNoDataView {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        [self setHidden:YES];
        if (weakSelf.selfSuperView) {
            [self removeFromSuperview];
        }
    }];
}

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"isNoData"];
}
@end
